package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.constant.CacheConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.domain.User;
import cn.itsource.ymcc.feign.LoginFeign;
import cn.itsource.ymcc.mapper.UserMapper;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.IUserService;
import cn.itsource.ymcc.utils.AssertUtil;
import cn.itsource.ymcc.utils.BitStatesUtils;
import cn.itsource.ymcc.vo.UserRegisterVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author zongcj
 * @since 2023-09-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private LoginFeign loginFeign;
    @Autowired
    private UserMapper userMapper;

//    @Transactional//只能管本地的
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public JsonResult register(UserRegisterVo userRegisterVo) {
        //验证  手机号是否注册
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, userRegisterVo.getMobile())
        );
        AssertUtil.isNull(user,"该手机号以被注册!");
        //验证  短信验证有没有失效
        Boolean aBoolean = redisTemplate.hasKey(CacheConstants.REGISTER_PREFIX + userRegisterVo.getMobile());
        AssertUtil.isTrue(aBoolean,"验证以过期！");

        String code = redisTemplate.opsForValue().get(CacheConstants.REGISTER_PREFIX + userRegisterVo.getMobile()).toString();
        AssertUtil.isTrue(userRegisterVo.getSmsCode().equalsIgnoreCase(code),"验证码输入错误");

        //保存用户信息
        User userRegister = new User();
        userRegister.setCreateTime(new Date());
        userRegister.setPhone(userRegisterVo.getMobile());
        userRegister.setNickName(userRegisterVo.getMobile());
        userRegister.setSecLevel(0);//
        //位状态 ： 注册成功
        Long bitState = BitStatesUtils.addState(0L, BitStatesUtils.OP_REGISTED);
        System.out.println(Integer.toBinaryString(bitState.intValue()));
        //激活
        bitState = BitStatesUtils.addState(bitState, BitStatesUtils.OP_AUTHED_PHONE);
        System.out.println(Integer.toBinaryString(bitState.intValue()));
        userRegister.setBitState(bitState); //todo
        userMapper.insert(userRegister);

        Login login = new Login();
        login.setUsername(userRegisterVo.getMobile());
        //密码加密
        String password = userRegisterVo.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        login.setPassword(bCryptPasswordEncoder.encode(password));
        login.setType(userRegisterVo.getRegChannel());//0是后台，1是前台
        login.setEnabled(RConst.Num.INT_1);
        //在保存loginInfo
        JsonResult jsonResult = loginFeign.saveOrUpdate(login);

        //java.lang.Integer cannot be cast to java.lang.Long
        Integer loginId = (Integer)jsonResult.getData();//我们使用openFeign调用返回的数据如果是long会默认给你转换为Integer
        //修改user 添加 loginId
        userRegister.setLoginId(loginId.longValue());
        userMapper.updateById(userRegister);
        return JsonResult.success();
    }
}
